import com.why.WhyCacheCloudRedissionApp;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;

@RunWith(SpringRunner.class)
@SpringBootTest(
        classes = WhyCacheCloudRedissionApp.class)
@AutoConfigureMockMvc
@TestPropertySource(
        locations = "classpath:application.yaml")
@Slf4j
public class RedissonBloomFilter {
    @Resource
    private RedissonClient redissonClient;

    @Test
    public void bloomFilterDemo() {
        StopWatch stopwatch = new StopWatch();
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter("bloom-filter");
        //初始化，容器10000.容错率千分之一
        bloomFilter.tryInit(10000, 0.001);
        stopwatch.start("add");
        //添加10000个
        for (int i = 0; i < 10000; i++) {
            bloomFilter.add("redisson" + i);
        }
        stopwatch.stop();
        //用来统计误判的个数
        int count = 0;
        //查询不存在的数据一千次
        stopwatch.start("check");
        for (int i = 0; i < 1000; i++) {
            if (bloomFilter.contains("redis" + i)) {
                count++;
            }
        }
        stopwatch.stop();
        log.info("判断错误的个数：{}", count);
        log.info("redisson9999是否在过滤器中存在：{}", bloomFilter.contains("redisson9999"));
        log.info("redisson11111是否在过滤器中存在：{}", bloomFilter.contains("redisson11111"));
        log.info("预计插入数量：{}", bloomFilter.getExpectedInsertions());
        log.info("容错率：{}", bloomFilter.getFalseProbability());
        log.info("hash函数的个数：{}", bloomFilter.getHashIterations());
        log.info("插入对象的个数：{}", bloomFilter.count());
    }

    /**
     * result
     * 判断错误的个数：1
     * redisson9999是否在过滤器中存在：true
     * redisson11111是否在过滤器中存在：false
     * 预计插入数量：10000
     * 容错率：0.001
     * hash函数的个数：10
     * 插入对象的个数：9995
     *
     * 效率较低
     */
}